﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using LS.Api.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace LS.Api.Helper
{
    /// <summary>
    /// webapi权限验证（jwt）
    /// </summary>
    public class ApiAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 指示指定的控件是否已获得授权
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var authHeader = from t in actionContext.Request.Headers where t.Key == "token" select t.Value.FirstOrDefault();
            if (authHeader != null)
            {
                string token = authHeader.FirstOrDefault();
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        //string secureKey = System.Configuration.ConfigurationManager.AppSettings["SecureKey"];
                        string secret = ConfigurationManager.AppSettings["SecureKey"];
                        //secret需要加密
                        IJsonSerializer serializer = new JsonNetSerializer();
                        IDateTimeProvider provider = new UtcDateTimeProvider();
                        IJwtValidator validator = new JwtValidator(serializer, provider);
                        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                        IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

                        var json = decoder.DecodeToObject<AuthInfo>(token, secret, true);
                        if (json != null)
                        {
                            //判断口令过期时间
                            if (json.ExpiryDateTime < DateTime.Now)
                            {
                                return false;
                            }
                            //供controller调用：
                            //AuthInfo authInfo = this.RequestContext.RouteData.Values["auth"] as AuthInfo;
                            //authInfo.Roles
                            actionContext.RequestContext.RouteData.Values.Add("auth", json);

                            return true;
                        }
                        return false;
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 处理授权失败的请求
        /// </summary>
        /// <param name="actionContext"></param>
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            //ApiJsonResult res = new ApiJsonResult(1, "无访问权限");
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, new ApiJsonResult(ApiResult.NoAuth, "无访问权限"), "application/json");
        }

    }
}